package JAVA300.第十章IO;

import java.io.*;

/**
 * p180-封装拷贝及释放资源代码
 */

public class MyFileUtil {
    public static void main(String[] args) {
        //文件到文件
        try {
            InputStream is = new FileInputStream("IOTest01.txt");//内部new了file对象了
            OutputStream os = new FileOutputStream("IOTest01_MyFileUtil.txt");
            CopyFile(is,os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //文件到字节数组
        byte[] out= null;
        try {
            InputStream is1 = new FileInputStream("testpic.png");
            ByteArrayOutputStream boas = new ByteArrayOutputStream();
            CopyFile(is1,boas);
            out = boas.toByteArray();
            System.out.println(out.length);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        //字节数组到文件
        try {
            InputStream is2 = new ByteArrayInputStream(out);
            OutputStream os = new FileOutputStream("testpic_MyFileUtil.png");
            CopyFile(is2,os);


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    //from IO_Study05_Method--实现给输出输入流即可完成 不用判断是哪类流
    public static void CopyFile(InputStream is,OutputStream os){

        try {
            int len;
            byte[] flush = new byte[1024];
            while ((len = is.read(flush)) != -1){
                os.write(flush,0,len);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            close(is,os);
        }

    }

    public static void close(InputStream is,OutputStream os){
        //两个
        if (null != os){
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if (null != is){
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    //close方法继承于closable 所以直接改成父类
    //另外，为此后可以关闭多个流，采用可变参数
    public static void close_full(Closeable... ios){
        for (Closeable io:ios){
            if (null != io){
                try {
                    io.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }
    }
}
